<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="btn" >添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in arr" :key="item.id">
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      name: '',
      age: 0,
      gender: '',
      edit_id: 0,
      arr: []
    }
  },
  methods: {
    // 添加/编辑
    btn () {
      if (this.name.trim().length === 0 || this.age === 0 || this.gender === '') return alert('请填写信息')
      if (this.edit_id) {
        // 编辑
        const i = this.arr.findIndex(el => el.id === this.edit_id)
        this.arr[i].name = this.name
        this.arr[i].age = this.age
        this.arr[i].gender = this.gender
      } else {
        // 添加
        const id = this.arr.length ? this.arr[this.arr.length - 1].id + 1 : 1
        this.arr.push({
          id,
          name: this.name,
          age: this.age,
          gender: this.gender
        })
      }
      // 赋初值
      this.name = ''
      this.age = 0
      this.gender = ''
      this.edit_id = 0
      alert('操作成功')
    },

    // 编辑赋值
    edit (id) {
      const i = this.arr.findIndex(el => el.id === id)
      this.name = this.arr[i].name
      this.age = this.arr[i].age
      this.gender = this.arr[i].gender
      this.edit_id = id
    },

    // 删除
    del (id) {
      this.arr.splice(this.arr.findIndex(el => el.id === id), 1)
    }
  }
}
</script>
